package cn.jn.lhm.netty.part08.chat.protocol;

import cn.jn.lhm.netty.part08.chat.message.LoginRequestMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/10/30 - 0:33
 **/
public class TestMessageCodec {
    public static void main(String[] args) throws Exception {
        MessageCodec messageCodec = new MessageCodec();
        EmbeddedChannel channel = new EmbeddedChannel(
                new LoggingHandler(LogLevel.DEBUG),
                new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0),
                messageCodec
        );

        // encode
        LoginRequestMessage user = new LoginRequestMessage("zhangSan", "123456");
        channel.writeOutbound(user);

        // decode
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        messageCodec.encode(null, user, buffer);

        // 这里是测试半包的问题
        ByteBuf buf1 = buffer.slice(0, 100);
        buf1.retain();
        ByteBuf buf2 = buffer.slice(100, buffer.readableBytes() - buf1.readableBytes());

        channel.writeInbound(buf1);
        channel.writeInbound(buf2);
    }
}
